const cloud = require('@alipay/faas-server-sdk');

exports.main = async (event, context) => {
  // 初始化
  cloud.init();
  const db = cloud.database();
  const { OPENID } = cloud.getAlipayContext();
  if (event.garBageName) {
    const historyList = await db.collection('garbageSearchHistory').where({ _openid: OPENID })
      .orderBy('searchTime', cloud.Sort.ASC)
      .get();
    if (historyList) {
      const list = historyList.filter((item) => item.garBageName == event.garBageName);
      if (list && list.length >= 1) {
        await db.collection('garbageSearchHistory').doc(list[0]._id)
          .update({
            data: {
              searchTime: Date.now(),
              garBageName: event.garBageName
            }
          });
      } else if (historyList.length >= 10) {
        await db.collection('garbageSearchHistory').doc(historyList[0]._id)
          .update({
            data: {
              searchTime: Date.now(),
              garBageName: event.garBageName
            }
          });
      } else {
        await db.collection('garbageSearchHistory')
          .add({
            data: {
              searchTime: Date.now(),
              garBageName: event.garBageName
            }
          });
      }
    } else {
      await db.collection('garbageSearchHistory')
        .add({
          data: {
            searchTime: Date.now(),
            garBageName: event.garBageName
          }
        });
    }
    return await db.collection('garbageSorting').where({
      garBageName: db.RegExp({
        regexp: event.garBageName
      })
    })
      .limit(10)
      .get();
  } else {
    return await db.collection('garbageSorting').where({
      ...event
    })
      .limit(10)
      .get();
  }
};